const { defineConfig } = require('@vue/cli-service')
const BodyParser = require('body-parser')
const Mock = require('mockjs')

const data = Mock.mock({
  'cartList|50': [
    {
      id: '@id()',
      img: '@image(150x150, @color(), @city())',
      count: 0,
      title: '@ctitle()',
      desc: '@cword(30)',
      price: '@integer(1, 100)',
      'type|+1': [1, 0], // 1. 有货 0: 没有货
    },
  ],
})

const UserInfo = [
  {
    username: 'admin',
    password: '123',
  },
  {
    username: 'super-admin',
    password: '321',
  },
]

module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    // proxy: {
    //   '/api': {
    //     target: 'http://localhost:3000',
    //     pathRewrite: {
    //       '^/api': '',
    //     },
    //   },
    // },
    proxy: 'http://localhost:3000',
    setupMiddlewares(middlewares, { app }) {
      app.use(BodyParser.json())

      // 1. 登陆接口
      app.post('/api/login', (req, res) => {
        const { username, password } = req.body
        // console.log('username:', username)
        // console.log('password:', password)
        const loginStatus = UserInfo.some((v) => v.username === username && v.password === password)
        // console.log('loginStatus:', loginStatus)
        if (loginStatus) {
          res.json({
            code: 1,
            msg: 'suceess',
            data: {
              token: `${username}_123`,
            },
          })
        } else {
          res.json({
            code: -1,
            msg: '登陆失败，请重新尝试',
          })
        }
      })

      // 2. 列表接口
      app.get('/api/list', (req, res) => {
        const { page = 1, size = 10 } = req.query
        res.json({
          code: 0,
          msg: 'success',
          data: { total: data.cartList.length, list: data.cartList.slice((page - 1) * size, page * size) },
        })
      })

      return middlewares
    },
  },
})
